//
//  QDLoginVC.m
//  QuDanOEM
//
//  Created by wmz on 2021/11/8.
//

#import "QDLoginVC.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "WXUntils.h"
#import "AppDelegate.h"
#import "QDLoginNetWork.h"
API_AVAILABLE(ios(13.0))
@interface QDLoginVC ()<ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding,WXApiDelegate>
@property (weak, nonatomic) IBOutlet BaseButton *areaBTN;
@property (weak, nonatomic) IBOutlet BaseTextField *codeTF;
@property (weak, nonatomic) IBOutlet BaseTextField *phoneTF;
@property (weak, nonatomic) IBOutlet BaseButton *CodeBTN;
@property (weak, nonatomic) IBOutlet BaseButton *confirmBTN;
@property (weak, nonatomic) IBOutlet BaseButton *qqBTN;
@property (weak, nonatomic) IBOutlet YYLabel *protocolLB;
@property (weak, nonatomic) IBOutlet BaseButton *wxBTN;
@property (weak, nonatomic) IBOutlet BaseButton *closeBTN;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (assign, nonatomic, getter=isCodeLogin) BOOL codeLogon;
@property (weak, nonatomic) IBOutlet BaseTextField *passwordTF;
@end

@implementation QDLoginVC

- (void)hd_setupViews{
    @HDWeakify(self)
    self.view.backgroundColor = PostColor(0xFAFAFC);
    self.codeLogon = YES;
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"登录即表示同意《用户协议》和《隐私政策》"];
    text.yy_font = wFontSize(15);
    text.yy_color =  wColor_3;
    text.yy_alignment = NSTextAlignmentCenter;
    [text yy_setTextHighlightRange:[text.string rangeOfString:@"《用户协议》"]
                             color:wColor_Main
                   backgroundColor:[UIColor whiteColor]
                         tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        [PostWindow pushWeb:@"http://www.baidu.com" title:@"用户协议条款"];
    }];
    [text yy_setTextHighlightRange:[text.string rangeOfString:@"《隐私政策》"]
                             color:wColor_Main
                   backgroundColor:[UIColor whiteColor]
                         tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        [PostWindow pushWeb:@"http://www.baidu.com"  title:@"隐私协议"];
    }];
    self.protocolLB.attributedText = text;
    
    [self.areaBTN TagSetImagePosition:PostBtnPositionRight spacing:3];
    
    if (@available(iOS 12.0, *))
        self.codeTF.textContentType = UITextContentTypeOneTimeCode;
    
    if (@available(iOS 13.0, *)) {
        self.qqBTN.hidden = NO;
        self.qqBTN.add_event(^(UIView * _Nonnull sender) {
            @HDStrongify(self)
            [self appleClick];
        });
    } else {
        self.qqBTN.hidden = YES;
    }
    
    if (![WXApi isWXAppInstalled])
        self.wxBTN.hidden = YES;
    
    self.confirmBTN.add_event(^(UIView * _Nonnull sender) {
        @HDStrongify(self)
        [self loginRequestAction];
    });
    
    self.phoneTF.add_event(^(UIView * _Nonnull sender) {
        @HDStrongify(self)
        [self userInableAction];
    });
    
    self.codeTF.add_event(^(UIView * _Nonnull sender) {
        @HDStrongify(self)
        [self userInableAction];
    });
    
    self.passwordTF.add_event(^(UIView * _Nonnull sender) {
        @HDStrongify(self)
        [self userInableAction];
    });
    
    self.confirmBTN.add_bgBackgroundColor(wColor_9);
    self.confirmBTN.enabled = false;
    
#ifdef DEBUG
    self.phoneTF.text = @"15323631784";
    self.codeTF.text = @"100001";
    self.confirmBTN.add_bgBackgroundColor([UIColor bm_colorGradientChangeWithSize:CGSizeMake(PostWidth - 64, 40) direction:PageGradientChangeDirectionLevel startColor:PostColorP(0xFF5121,1) endColor:PostColorP(0xFFC021,1)]);
    self.confirmBTN.enabled = true;
#endif
}

- (void)userInableAction{
    BOOL success = self.isCodeLogin ? (self.phoneTF.text.length && self.codeTF.text.length) : (self.phoneTF.text.length && self.passwordTF.text.length);
    self.confirmBTN.backgroundColor = success ? [UIColor bm_colorGradientChangeWithSize:CGSizeMake(PostWidth - 64, 40) direction:PageGradientChangeDirectionLevel startColor:PostColorP(0xFF5121,1) endColor:PostColorP(0xFFC021,1)]:wColor_9;
    self.confirmBTN.enabled = success;
}

- (IBAction)changeAction:(UIButton *)sender {
    self.codeLogon = !self.isCodeLogin;
    sender.add_title(self.isCodeLogin?@"密码登录":@"验证码登录");
}

- (void)appleClick API_AVAILABLE(ios(13.0)){
    ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc]init];
    ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
    request.requestedScopes = @[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail];
    ASAuthorizationController *auth = [[ASAuthorizationController alloc]initWithAuthorizationRequests:@[request]];
    auth.delegate = self;
    auth.presentationContextProvider = self;
    [auth performRequests];
}

///返回
- (IBAction)dissmissAction:(id)sender {
    
    [PostManage.shareInstance loginTUIM:nil];
    
    if (self.presentingViewController)
        [self dismissViewControllerAnimated:YES completion:nil];
}

/// 微信登录
- (IBAction)wxLoginAction:(id)sender {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.wxDelegate = self;
    //判断微信是否安装
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"App";
    [WXApi sendAuthReq:req viewController:self delegate:self completion:^(BOOL success) {
        
    }];
}

///发送验证码
- (IBAction)codeSendAction:(BaseButton *)sender {
    if (!GNStringNotEmpty(self.phoneTF.text)) {
        PostInfo(self.phoneTF.placeholder); return;
    }
    [QDLoginNetWork.shareInstance requestLoginSendCode:@{@"mobile":self.phoneTF.text} viewController:self andBlock:^(id  _Nullable data, BOOL result) {
        if (result) {
            PostSuccess(@"发送成功");
            [sender timeFailBeginFrom:60];
        }
    }];
}

///登录接口
- (void)loginRequestAction{
    if (!GNStringNotEmpty(self.phoneTF.text)) {
        PostInfo(self.phoneTF.placeholder); return;
    }
    
    if (self.isCodeLogin) {
        if (!GNStringNotEmpty(self.codeTF.text)) {
            PostInfo(self.codeTF.placeholder); return;
        }
    }else{
        
        if (!GNStringNotEmpty(self.passwordTF.text)) {
            PostInfo(self.passwordTF.placeholder); return;
        }
    }

    if (![PostCheckTool checkMobile:self.phoneTF.text]) {
        PostInfo(@"请输入正确的手机号") return;
    }
    
    PostHudShow(@"登录中...", self.view)
    if (self.isCodeLogin) {
        [QDLoginNetWork.shareInstance requestLoginApp:@{@"mobile":self.phoneTF.text,@"code":self.codeTF.text} viewController:self andBlock:^(id  _Nullable data, BOOL result) {
            if (result) {
                [self thirdLogin:@{} token:data];
            }else{
                PostHudHide(self.view)
            }
        }];
    }else{
        [QDLoginNetWork.shareInstance requestLoginAppWithPassword:@{@"acc":self.phoneTF.text,@"pwd":self.passwordTF.text} viewController:self andBlock:^(id  _Nullable data, BOOL result) {
            if (result) {
                [self thirdLogin:@{} token:data];
            }else{
                PostHudHide(self.view)
            }
        }];
    }
}

- (void)thirdLogin:(NSDictionary*)data token:(NSString*)token{
    if (!token) return;
    if (token) PostManage.shareInstance.token = token;
    [PostManage.shareInstance updateUser:^(id  _Nullable data, BOOL result) {
        PostHudHide(self.view)
        PostSuccess(@"登录成功")
        [self dissmissAction:nil];
    }];
}

///苹果登录deleagte
-(ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return self.view.window;
}

-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]){
//        ASAuthorizationAppleIDCredential *apple = authorization.credential;
//        NSPersonNameComponents *fullName = apple.fullName;
//        NSString *userID = apple.user;
//        NSString *email = apple.email;
//        NSData *identityToken = apple.identityToken;
//        NSString * str  =[[NSString alloc] initWithData:identityToken encoding:NSUTF8StringEncoding];
    }
}

-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    PostInfo(@"登录失败,请稍后再试");
}

- (void)setCodeLogon:(BOOL)codeLogon{
    _codeLogon = codeLogon;
    self.codeView.hidden = !codeLogon ;
    self.passwordView.hidden = codeLogon;
}

- (SAViewControllerNaviType)customNaviType{
    return SAViewControllerNaviTypeHide;
}





@end
